<?php

namespace app\api\middleware;

use thans\jwt\exception\JWTException;
use thans\jwt\exception\TokenBlacklistGracePeriodException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\middleware\BaseMiddleware;

class AuthJwt extends BaseMiddleware
{
    public function handle($request, \Closure $next)
    {
        // OPTIONS请求直接返回
        if ($request->isOptions()) {
            return response();
        }
        
        // 验证token
        try {
            $payload = $this->auth->auth();
            $user = [
                'user_id' => $payload['user_id']->getValue(),
            ];
            // $user = [
            //     'user_id' => 51,
            // ];
            $request->user = $user;
        } catch (TokenExpiredException $e) { // 捕获token过期
            // 尝试刷新token
            try {
                $this->auth->setRefresh();
                $token = $this->auth->refresh();
                $payload = $this->auth->auth(false);

                $user = [
                    'user_id' => $payload['user_id']->getValue(),
                ];

                $request->user = $user;

                $response = $next($request);
                $response->header(['is_expire' => 1]);
                return $this->setAuthentication($response, $token);
            } catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期
                $payload = $this->auth->auth(false);

                $user = [
                    'user_id' => $payload['user_id']->getValue(),
                ];

                $request->user = $user;

                return $next($request);
            }
        } catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期
            $payload = $this->auth->auth(false);
            // $request->uid = $payload['uid']->getValue();

            $user = [
                'user_id' => $payload['user_id']->getValue(),
            ];

            $request->user = $user;
        }catch (JWTException $e){
            return  json(['code' => $e->getMessage(), 'msg' => $e->getMessage()]);
        }

        return $next($request);

    }
}